package com.ahwei.shop.auth.util;

import cn.hutool.http.ContentType;
import com.ahwei.r.R;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author：ahWei
 * Email: ahwei163@qq.com
 * Date: 2022-04-23 15:05:34
 * Description: 这是一个Java文件！
 */
@Component
public class ResponseUtils {
    @Resource
    private ObjectMapper objectMapper;
    /**
     * 响应json数据给前端
     * @param info ·
     * @param response ·
     * @throws IOException ·
     */
    public <T> void outWriter(R<T> info, int httpStatusValue, HttpServletResponse response) throws IOException {
        // 使用jackson工具将响应数据转换为json
        String json = objectMapper.writeValueAsString(info);
        // 设置响应编码 "application/json;charset=utf-8"
        response.setContentType(ContentType.JSON.toString(StandardCharsets.UTF_8));
        // 设置响应状态码
        response.setStatus(httpStatusValue);
        // 通过响应对象返回数据
        response.getWriter().write(json);
    }
}
